package main;

import java.awt.EventQueue;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.http.entity.mime.content.FileBody;

import tasks.Reportable;

public class MyFileBody extends FileBody {
	
	private final String game;
	private final String relPath;
	private final Reportable context;

	public MyFileBody(final File file, Reportable context, 
			String game, String relPath) {
        super(file);
        this.game = game;
        this.relPath = relPath;
        this.context = context;
    }
	
	@Override
	public void writeTo(OutputStream out) {
        if (out == null) {
            throw new IllegalArgumentException("Output stream may not be null");
        }
        InputStream in = null;
        try {
        	in = new FileInputStream(this.getFile());
            byte[] tmp = new byte[4096];
            long len = 0;
            int l;
            while ((l = in.read(tmp)) != -1) {
                out.write(tmp, 0, l);
                len+=l;
                final long process = len;
                EventQueue.invokeLater(new Runnable(){
					@Override
					public void run() {
						context.reportFileProgress(game, relPath, process);
					}
                });
            }
            out.flush();
        } catch (IOException e) {
			e.printStackTrace();
		} finally {
            try{in.close();}catch(IOException e1){}
        }
	}

}
